<?php

class webjobs {

    private static function getInfo() {
        $retur = null;
        $retur['machine'] = trim($_SERVER['SERVER_NAME']) != "" ? trim($_SERVER['SERVER_NAME']) : trim($_SERVER['COMPUTERNAME']);
        $tmp = $_SERVER['PHP_SELF'];
        $tmp = str_ireplace("\\", "|", $tmp);
        $tmp = str_ireplace("/", "|", $tmp);
        $split = explode("|", $tmp);
        if (is_array($split)) {
            $count = count($split);
            $retur['job'] = $split[$count - 2];
        }
        return $retur;
    }

    private static function exec($status, $comment = "") {

        $info = self::getInfo();
        $ws = new SoapClient("http://sdca2adl/portal/webservices/webjobs.service.php?WSDL", array('login' => "", 'password' => "", "cache_wsdl" => WSDL_CACHE_NONE));
        try {
            $data = $ws->__call("setStatus", array(
                "server" => utf8_encode($info['machine']),
                "job" => utf8_encode($info['job']),
                "status" => utf8_encode($status),
                "comment" => utf8_encode($comment)
            ));
            return $data;
        } catch (Exception $e) {
            return $e;
        }
    }
    
    public static function started($comment = ""){
        return "\n\nSET webjob-status (started): ".self::exec("started", base64_encode($comment))."\n\n";
    }

    public static function failed($comment = ""){
        return "\n\nSET webjob-status (failed): ".self::exec("failed", base64_encode($comment))."\n\n";
    }
    
    public static function ended($comment = ""){
        if (trim($comment)!=""){
            $comment.= " ";
        }
        $comment.= "[".(int)(memory_get_peak_usage(false)/1024/1024)."MB / ".ini_get ("memory_limit")."]";
        return "\n\nSET webjob-status (ended): ".self::exec("ended", base64_encode($comment))."\n\n";
    }
    
    public static function progress($comment = ""){
        return "\n\nSET webjob-status (progress): ".self::exec("in progress", base64_encode($comment))."\n\n";
    }
    
}
